﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Fcdbas.WinUI.Forms;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using Fcdbas.Platform.Interface;
using Fcdbas.WinUI.Common;
using Fcdbas.Core.Windows;
using Fcdbas.WinUI.Windows;
using Fcdbas.Platform.Properties;
using Fcdbas.Platform;
using Fcdbas.WinUI.Controls;
using Fcdbas.Core;

namespace Fcdbas.WinUI.Forms
{
    
    public partial class dlgReplace : cDialogWindow
    {
        enum SearchMode
        {
            Down,
            Up,
            UpToDown,
            DownToUp
        }
        enum MarchMode
        {
            All,
            Part
        }
        class SearchCondition
        {
            public bool UCase;
            public SearchMode SMode;
            public MarchMode MMode;
            public bool Selected;
            public string ColumnName;
        }
        private static List<string> findList = new List<string>();
        private static List<string> repList = new List<string>();
        GridView gridView;
        GridColumn column;
        private SearchCondition Scondition = new SearchCondition();
        public dlgReplace(GridColumn column)
        {
            InitializeComponent();
            this.gridView = column.View as GridView;
            this.column = column;
        }

        private void dlgReplace_Load(object sender, EventArgs e)
        {
            cbRange.Properties.Items.Clear();
            int idx = 0;
            for (int i = 0; i < gridView.Columns.Count; i++)
            {
                GridColumn col = gridView.Columns[i];
                if(col.FieldName == column.FieldName)
                    idx = i;
                cbRange.AddItem(col, col.Caption);
            }
            cbRange.SelectedIndex = idx;
            currentField = column.FieldName;
            EnableReplace(column.FieldName);
            foreach (string s in findList)
            {
                cbFindContent.Properties.Items.Add(s);
            }
            foreach (string s in repList)
            {
                cbReplaceContent.Properties.Items.Add(s);
            }
            Scondition.ColumnName = column.FieldName;
            Scondition.MMode = MarchMode.All;
            Scondition.SMode = SearchMode.Down;
            Scondition.UCase = false;
            Scondition.Selected = false;
            cbMatching.SelectedIndex = 0;
            cbSearchMode.SelectedIndex = 0;
            currentRowIdx = gridView.FocusedRowHandle;
        }

        private void chkUpper_CheckedChanged(object sender, EventArgs e)
        {
            Scondition.UCase = chkUpper.Checked;
        }
        private void EnableReplace(string columnName)
        {
            DataSourceBinding dsb = gridView.DataSource as DataSourceBinding;
            if (dsb == null)
                return;
            DataItem di = dsb.Columns.Find(p => p.ColumnName == columnName);
            if (di == null)
                return;
            bool editMethodAuthorized = dsb.IsUserModify;

            if (dsb.Updates == Fcdbas.Platform.Enums.UpdatesSql.ReadOnly)
            {
                btnList.Enabled = false;
                btnReplaceAll.Enabled = false;
            }
            else
            {
                if (di.Flags == Platform.Enums.DataItemFlags.ParentKey)
                    btnList.Enabled = btnReplaceAll.Enabled = false;
                else
                    btnList.Enabled = btnReplaceAll.Enabled = !editMethodAuthorized || !(di.UpdateOption == Fcdbas.Platform.Enums.DataItemUpdate.NotAllowed);
            }     
        }
        private void chkSelected_CheckedChanged(object sender, EventArgs e)
        {
            Scondition.Selected = chkSelected.Checked;
        }

        private void cbSearchMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            bBegin = false;
            Scondition.SMode = (SearchMode)cbSearchMode.SelectedIndex;
        }

        private void cbMatching_SelectedIndexChanged(object sender, EventArgs e)
        {
            bBegin = false;
            Scondition.MMode = (MarchMode)cbMatching.SelectedIndex;
        }
        private bool bBegin = false;
        private int currentRowIdx = -1;
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (!findList.Contains(cbFindContent.Text))
            {
                findList.Add(cbFindContent.Text);
                cbFindContent.Properties.Items.Add(cbFindContent.Text);
            }
            if (!bBegin)
            {
                if (Scondition.SMode == SearchMode.DownToUp)
                    currentRowIdx = gridView.RowCount - 1;
                else if (Scondition.SMode == SearchMode.UpToDown)
                    currentRowIdx = 0;
                bBegin = true;
            }
            int[] selected = gridView.GetSelectedRows();
            GridColumn gc = cbRange.GetCurrentItem() as GridColumn;
            Type t = gc.ColumnType;
            if (t.GetGenericArguments().Length > 0)
                t = t.GetGenericArguments()[0];
            switch (Scondition.SMode)
            {
                case SearchMode.Down :
                case SearchMode.UpToDown:
                    if (currentRowIdx == gridView.RowCount - 1)
                        return;
                    for (int i = currentRowIdx; i < gridView.RowCount; i++)
                    {
                        if (Scondition.Selected)
                        {
                            if (!selected.ToList().Contains(i))
                                continue;
                        }
                       // IEntity en = gridView.GetRow(i) as IEntity;
                        object v = gridView.GetRowCellValue(i, currentField);
                        if (March(v, this.cbFindContent.Text,t))
                        {
                            currentRowIdx = i;
                            gridView.FocusedRowHandle = i;
                            this.ShowMessage("找到匹配的记录，记录号[%%1]", (i+1).ToString(), MessageBoxButtons.OK);
                            break;
                        }
                    }
                    break;
                case SearchMode.Up:
                case SearchMode.DownToUp:
                    if (currentRowIdx < 0)
                        return;
                    for (int i = currentRowIdx; i >= 0; i--)
                    {
                        if (Scondition.Selected)
                        {
                            if (!selected.ToList().Contains(i))
                                continue;
                        }
                        object v = gridView.GetRowCellValue(i, currentField);
                        //IEntity en = gridView.GetRow(i) as IEntity;
                        if (March(v, this.cbFindContent.Text,t))
                        {
                            currentRowIdx = i;
                            gridView.FocusedRowHandle = i;
                            this.ShowMessage("找到匹配的记录，记录号[%%1]", (i+1).ToString(), MessageBoxButtons.OK);
                            break;
                        }
                    }
                    break;
                
            }

        }
        private bool March(object v, string Content,Type t)
        {
            //if (en[currentField] == null)
            if (v == null)
            {
                if (string.IsNullOrEmpty(Content))
                    return true;
                else
                    return false;
            }
            string dest = v.ToString();// en[currentField].ToString();
            if (Scondition.MMode == MarchMode.All)
            {
                object de = Convert.ChangeType(Content, t);
                return de.Equals(v);
                //int c = string.Compare(dest, Content, !Scondition.UCase);
                //if (c == 0)
                //    return true;
                //else
                //    return false;
            }
            else
            {
                if (dest.IndexOf(Content) >= 0)
                    return true;
                else
                    return false;
            }
        }
        private string currentField;
        private void cbRange_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbRange.GetCurrentItem() != null)
            {
                currentField = ((GridColumn)cbRange.GetCurrentItem()).FieldName;
                EnableReplace(currentField);
            }
        }

        private void cbFindContent_EditValueChanged(object sender, EventArgs e)
        {
            bBegin = false;
        }

        private void btnList_Click(object sender, EventArgs e)
        {
            if (currentRowIdx < 0 || currentRowIdx > gridView.RowCount)
                return;
            IEntity en = gridView.GetRow(currentRowIdx) as IEntity;
            if (en == null)
                return;
            GridColumn gc = cbRange.GetCurrentItem() as GridColumn;
            DataSourceBinding dsb = gridView.DataSource as DataSourceBinding;
            dsb.DataRecordModified(en);
            //en[gc.FieldName] = Convert.ChangeType(this.cbReplaceContent.Text, gc.ColumnType);
            Type t = gc.ColumnType;
            if (t.GetGenericArguments().Length > 0)
                t = t.GetGenericArguments()[0];
            //if(en[gc.FieldName] != null)
            //    t = en[gc.FieldName].GetType();
            try
            {
                en[gc.FieldName] = Convert.ChangeType(this.cbReplaceContent.Text, t);
            }
            catch (Exception ex)
            {
                this.Error("数据类型转换出错，输入的数据不是合法的数据！");
                return;
            }
            gridView.RefreshData();
            BaseForm frm = gridView.GridControl.FindForm() as BaseForm;
            if (frm != null && frm.MainForm != null)
                frm.MainForm.EnableSave = true;
        }

        private void btnReplaceAll_Click(object sender, EventArgs e)
        {
            DataSourceBinding dsb = gridView.DataSource as DataSourceBinding;
            GridColumn gc = cbRange.GetCurrentItem() as GridColumn;
            int[] selected = gridView.GetSelectedRows();
            switch (Scondition.SMode)
            {
                case SearchMode.Down:
                case SearchMode.UpToDown:
                    if (currentRowIdx == gridView.RowCount - 1)
                        return;
                    for (int i = currentRowIdx; i < gridView.RowCount; i++)
                    {
                        if (Scondition.Selected)
                        {
                            if (!selected.ToList().Contains(i))
                                continue;
                        }
                        Type t = gc.ColumnType;
                        if (t.GetGenericArguments().Length > 0)
                            t = t.GetGenericArguments()[0];
                        object v = gridView.GetRowCellValue(i, currentField);
                        IEntity en = gridView.GetRow(i) as IEntity;
                        if (March(v, this.cbFindContent.Text,t))
                        {
                            currentRowIdx = i;
                            dsb.DataRecordModified(en);
                           
                            //if(en[gc.FieldName] != null)
                            //    t = en[gc.FieldName].GetType();
                            try
                            {
                                en[gc.FieldName] = Convert.ChangeType(this.cbReplaceContent.Text, t);
                            }
                            catch (Exception ex)
                            {
                                this.Error("数据类型转换出错，输入的数据不是合法的数据！");
                                return;
                            }
                           // en[gc.FieldName] = Convert.ChangeType(this.cbReplaceContent.Text, t);
                            //en[gc.FieldName] = Convert.ChangeType(this.cbReplaceContent.Text, gc.ColumnType);
                            
                        }
                    }
                    break;
                case SearchMode.Up:
                case SearchMode.DownToUp:
                    if (currentRowIdx < 0)
                        return;
                    for (int i = currentRowIdx; i >= 0; i--)
                    {
                        if (Scondition.Selected)
                        {
                            if (!selected.ToList().Contains(i))
                                continue;
                        }

                        IEntity en = gridView.GetRow(i) as IEntity;
                        Type t = gc.ColumnType;
                        if (t.GetGenericArguments().Length > 0)
                            t = t.GetGenericArguments()[0];
                        object v = gridView.GetRowCellValue(i, currentField);
                        if (March(v, this.cbFindContent.Text,t))
                        {
                            currentRowIdx = i;
                            dsb.DataRecordModified(en);
                            try
                            {
                                en[gc.FieldName] = Convert.ChangeType(this.cbReplaceContent.Text, t);
                            }
                            catch (Exception ex)
                            {
                                this.Error("数据类型转换出错，输入的数据不是合法的数据！");
                                return;
                            }
                            //if(en[gc.FieldName] != null)
                            //    t = en[gc.FieldName].GetType();
                           // en[gc.FieldName] = Convert.ChangeType(this.cbReplaceContent.Text, t);
                            //en[gc.FieldName] = Convert.ChangeType(this.cbReplaceContent.Text, gc.ColumnType);
                        }
                    }
                    break;

            }
            gridView.RefreshData();
        }
    }
}
